import { _form } from './form.js'
import { _query, _empty, _append, dom, _toggleClassName } from './dom.js'
import { renderContent } from './renderContent.js'
import { _type, getValue, setValue, propsSplitChar } from '../utils/index.js'
import { fractalTypes } from '../svg/fractal/fractal.js'
import { transformTypes } from '../math/transform.js'
import { patternTypes, rotatableShape } from '../svg/renderShape.js' //shapeTypes
import { sortByOrder } from '../math/arraySort.js'
import { colorTypes } from '../color/index.js'
import { _tabs } from './tabs.js'
import { axisTypes } from '../svg/axis/axis.js'
import { treeCurveTypes } from '../svg/fractal/tree.js'
import { pathModeTypes, curveTypes, mirrorTypes } from '../svg/path2.js'
const layoutTypes = ['0', '2x2', '4x4', '10x8', '18x12']
const monocolors = ['none', 'black', 'gray', 'red', 'blue', 'purple', 'green']//,'yellow'
const strokeTypes = monocolors
const fillTypes = monocolors
const typesMap = {
    fractalTypes, transformTypes, patternTypes, colorTypes,
    strokeTypes, fillTypes, axisTypes, layoutTypes, treeCurveTypes,
    pathModeTypes, curveTypes, mirrorTypes
}
// 参数顺序 
const keysOrder = ['shape', 'n', 'r', 'a', 'm',
    'pathModel', 'curve',
    'transform', 'mirror', 'fractal',
    'vertex', 'centre', 'excircle', 'incircle', 'labels', 'linkCross',
    'pattern',
    'color', 'colorful', 'alpha',
    'props_.*?',
    'axis', 'layout']
// 默认参数
const defaultProps = [
    {
        field: 'shape',
        type: 'string',
        disabled: true
    },
    {
        field: 'n',
        type: 'number',
        min: 1,
        max: 999
    }, {
        field: 'r',
        type: 'number',
        min: 1,
        max: 999999
    },
    {
        field: 'a',
        type: 'number',
    },
    {
        field: 'm',
        min: 1,
        max: 999
    }
]

// 保留属性
const keepProps = (obj, t) => {
    return ['number', 'string', 'boolean'].includes(_type(obj[t]))
}


// 深度覆盖
const deepAssign = (obj, obj2) => {
    Object.keys(obj).forEach(t => {
        if (obj2.hasOwnProperty(t)) {
            if (_type(obj[t]) === 'object' && _type(obj2[t]) === 'object') {
                Object.assign(obj[t], obj2[t])
            } else {
                obj[t] = obj2[t]
            }
        }
    })
    return obj
}

export const _inspector = (t) => {
    // debugger
    let { content, name } = t
    let { shapes, axis } = content
    let shapeObj = shapes[0] || {}
    // 默认参数 旋转角度
    if (rotatableShape.includes(shapeObj.shape)) {
        if (shapeObj.a === undefined) {
            shapeObj.a = 0
        }
    };
    // 加颜色参数
    if (!shapeObj.color && !shapeObj.props
        && ['polygon', 'star', 'spiral', 'triangleLeaf'].includes(shapeObj.shape)
        && ['fractal', 'pathPoints', 'vertex'].some(t => shapeObj[t])) {
        shapeObj.color = 'colorCircle'
    }





    let keys = Object.keys(shapeObj).filter(t => keepProps(shapeObj, t));

    // 多层级属性
    ['props', 'vertex', 'centre', 'excircle', 'incircle', 'labels'].forEach(t => {
        let obj = shapeObj[t]
        if (obj) {
            let props = Object.keys(obj)
            if (props.length) {
                props.filter(u => keepProps(obj, u)).forEach(u => {
                    keys.push(`${t}${propsSplitChar}${u}`)
                })
            } else {
                // 是否
                keys.push(t)

            }

        }
    })

    // 坐标轴
    keys.push('axis', 'layout')



    keys = sortByOrder(keys, keysOrder)
    console.log(keys)

    let formData = {
        // title: shapeObj.shape,
        fields: keys.map(field => {
            let value = field === 'axis' ? getValue(axis, field) : getValue(shapeObj, field)  // shapeObj[field]
            let type = _type(value)

            // 空对象转布尔
            if (type === 'object' && Object.keys(value).length === 0) {
                type = 'checkbox'
                value = true
            }

            let item = {
                ...defaultProps.find(t => t.field === field),
                field,
                label: field,
                value,
                type,
                disabled: /([a-z]+_)?shape$/.test(field)  //field === 'shape' 
            };

            // 下拉选项            
            ['fractal', 'transform', 'pattern', 'color', 'stroke',
                'fill', 'axis', 'layout', 'treeCurve', 'pathMode', 'curve', 'mirror'].forEach(t => {
                    let reg = new RegExp(`([a-z]+_)?${t}$`)
                    if (reg.test(field)) { //field === t
                        item.options = typesMap[`${t}Types`].map(t => {
                            return {
                                label: t,
                                value: t
                            }
                        })
                        item.type = 'select'
                    }
                })
            return item
        }),
        op: [{
            type: 'btn',
            text: 'rerender',
            className: 'success',
            click: (e, { model }) => {
                let newModel = {}
                Object.keys(model).forEach(t => setValue(newModel, t, model[t]))
                let shapes = t.content.shapes.filter(t => model.shape === t.shape)
                shapes.forEach(t => deepAssign(t, newModel))

                // 坐标轴
                t.content.axis = {
                    shape: model.axis,
                    grid: {}
                }
                // 排版
                t.content.layout = model.layout === '0' ? null : model.layout

                let { content, isHtml } = renderContent(t)
                let viewer = _query(".screen-viewer")
                let panel = _query(`.panel[name="${name}"]`, viewer)
                _empty(panel)
                _append(panel, content)
            }
        }]
    }
    console.log(formData)


    let tabs = _tabs({
        tabs: [{
            title: 'input',
            name: 'tab_input',
            content: () => {
                let str = JSON.stringify(t.content)
                // return str.split('",').join('",<br>')
                return str.replace(/["}\]],/g, (a) => `${a}<br>`)
            },
            contentType: 'html'
        }, {
            title: 'output',
            name: 'tab_output',
            content: () => {
                let panel = _query(`.screen-viewer .panel[name=${t.name}]`)
                let str = ""
                let firstchild = panel.firstChild
                if (/CANVAS/i.test(firstchild.nodeName)) {
                    str = firstchild.toDataURL('image/png')
                } else {
                    str = panel.innerHTML
                }
                return str
            }
        }],
        activeName: 'tab_input'
    }, {
        class: 'props'
    })
    return [_form(formData), tabs]
}